<?php
namespace lib;
class RedisPool {
    /**
     * @var \Swoole\Coroutine\Channel
     */
    protected $pool;
    
    /**
     * RedisPool constructor.
     * @param int $size 连接池的尺寸
     */
    function __construct($size = 2)
    {
        $config = new Config();
        $redisConfig = $config->redis;
        unset($config);
        $this->pool = new \Swoole\Coroutine\Channel($size);
        $redis = new \Swoole\Coroutine\Redis();
        $redis->setOptions(
            ['connect_timeout' => 10]
            );
        for ($i = 0; $i < 2; $i++){
            $res = $redis->connect($redisConfig['host'], $redisConfig['port']);
            var_dump($res);
        }
        
        
        //$res = $redis->connect($redisConfig['host'], $redisConfig['port']);
        //var_dump($res);
        /* $res = $redis->auth($redisConfig['password']);
        var_dump($res);
        $this->put($redis);
        
        
        $redis = new \Swoole\Coroutine\Redis();
        $res = $redis->connect($redisConfig['host'], $redisConfig['port']);
        var_dump($res);
        $res = $redis->auth($redisConfig['password']);
        var_dump($res);
        $this->put($redis); */
        /* $config = new Config();
        $redisConfig = $config->redis;
        unset($config);
        
        $this->pool = new \Swoole\Coroutine\Channel($size);
        var_dump($redisConfig);
        $redis = new \Swoole\Coroutine\Redis();
        $res = $redis->connect($redisConfig['host'], $redisConfig['port']);
        var_dump(444);
        if ($res == false)
        {   var_dump('linn no');
            throw new \RuntimeException("failed to connect redis server.");
        }else{
            $res = $redis->auth($redisConfig['password']);
            if ($res == false)
            {   var_dump('password no');
                throw new \RuntimeException("failed to connect redis server.");
            }else
            {
                $this->put($redis);
            }
        }
        
        return;
        
        
        for ($i = 0; $i < $size; $i++)
        {
            $redis = new \Swoole\Coroutine\Redis();
            $res = $redis->connect($redisConfig['host'], $redisConfig['port']);
            if ($res == false)
            {
                throw new \RuntimeException("failed to connect redis server.");
            }else{
                $res = $redis->auth($redisConfig['password']);
                if ($res == false)
                {
                    throw new \RuntimeException("failed to connect redis server.");
                }else
                {
                    $this->put($redis);
                }
            }
            
            
        }

        var_dump($this->pool->capacity()); */
    }
    
    function put($redis)
    {
        $this->pool->push($redis);
    }
    
    function get()
    {
        return $this->pool->pop();
    }
}